from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from marshmallow import Schema,fields

app = Flask(__name__)

ma = Marshmallow()
ma.init_app(app)

class User(object):
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.created_at = datetime.now()
        self.friends = []
        self.books = []

class UserSchema(Schema):
    name = fields.String()
    email = fields.Email()
    created_at = fields.DateTime(format='%Y-%m-%d %H:%H:%S')

    # 自嵌套-->方式一：使用一个外部新声明的构造器类，可以指点序列化哪些字段
    # friends = fields.Nested(lambda: UserUserSchema(many=True, only=("name",)))
    friends = fields.Nested(lambda: UserUserSchema(many=True))

class UserUserSchema(Schema):
    name = fields.String()
    email = fields.String()

@app.route("/")
def index():
    #自嵌套
    user0 = User(name="小明",email="123@qq.com")
    user1 = User(name="小红",email="123@qq.com")
    user2 = User(name="小白",email="123@qq.com")
    user3 = User(name="小黑",email="123@qq.com")
    user0.friends=[user1,user2,user3]
    us = UserSchema()
    user0 = us.dump(user0)
    print(user0)
    """
    打印结果：
        {
            'name': '小明', 
            'friends':
                [
                    {'name': '小红', 'email': '123@qq.com'}, 
                    {'name': '小白', 'email': '123@qq.com'}, 
                    {'name': '小黑', 'email': '123@qq.com'}
                ],
            'email': '123@qq.com', 
            'created_at': '2021-03-06 00:00:37'
        }
    """

    return "hello"

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0" , port=5998)
